/**  
 * @Project: goicter Maven Webapp
 * @Package com.goicter.commons.utils
 * @Title: PojoMapperUtils.java
 * @Description: JSONת����
 *
 * @author: Eric Zheng
 * @date 2015-3-15 ����8:20:20
 * @Copyright: Eric Zheng JIMIOPEN.NET. All rights reserved.
 * @version V1.0   
 */
package com.goicter.commons.utils;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PojoMapperUtils {
	private static Logger log = LoggerFactory.getLogger(PojoMapperUtils.class);
	private static ObjectMapper m = new ObjectMapper();
	private static JsonFactory jf = new JsonFactory();

	public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) {
		try {
			return m.readValue(jsonAsString, pojoClass);
		} catch (JsonParseException e) {
			log.error("Json To Object Failure: " + e);
		} catch (JsonMappingException e) {
			log.error("Json To Object Failure: " + e);
		} catch (IOException e) {
			log.error("Json To Object Failure: " + e);
		}
		return null;
	}

	public static <T> Object fromJson(FileReader fr, Class<T> pojoClass) {
		try {
			return m.readValue(fr, pojoClass);
		} catch (JsonParseException e) {
			log.error("Json To Object Failure: " + e);
		} catch (JsonMappingException e) {
			log.error("Json To Object Failure: " + e);
		} catch (IOException e) {
			log.error("Json To Object Failure: " + e);
		}
		return null;
	}

	public static String toJson(Object pojo, boolean prettyPrint) {
		StringWriter sw = new StringWriter();
		try {
			JsonGenerator jg = jf.createJsonGenerator(sw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
			m.writeValue(jg, pojo);
		} catch (JsonGenerationException e) {
			log.error("Object To Json Failure: " + e);
		} catch (JsonMappingException e) {
			log.error("Object To Json Failure: " + e);
		} catch (IOException e) {
			log.error("Object To Json Failure: " + e);
		}
		return sw.toString();
	}

	public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint) {
		try {
			JsonGenerator jg = jf.createJsonGenerator(fw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
			m.writeValue(jg, pojo);
		} catch (JsonGenerationException e) {
			log.error("Object To Json Failure: " + e);
		} catch (JsonMappingException e) {
			log.error("Object To Json Failure: " + e);
		} catch (IOException e) {
			log.error("Object To Json Failure: " + e);
		}
	}
}

